/*
 * @lc app=leetcode.cn id=92 lang=javascript
 *
 * [92] 反转链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} left
 * @param {number} right
 * @return {ListNode}
 */
function reverse(prev, cur)  {
    if (!cur) return prev;
    tem = cur.next;
    cur.next = prev;
    reverse(cur, tem);
}
var reverseBetween = function(head, left, right) {
  const VNode = new ListNode(-1);
  VNode.next = head;

  let prev = VNode;
  for(i = 0; i < left - 1; i++) {
    prev = prev.next;
  }

  let rightNode = prev;
  for(i = 0; i < right - left + 1; i++) {
    rightNode = rightNode.next;
  }

  const leftNode = prev.next;
  const cur = rightNode.next;

  prev.next = null;
  rightNode.next = null;
  
  reverse(null, leftNode);
  prev.next = rightNode;
  leftNode.next = cur;

  return VNode.next;

};
// @lc code=end

